package com.nit.tools.doc;

import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerFontProvider;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import freemarker.template.TemplateException;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * 生成pdf工具类
 *
 * @author guoj
 * @date 2019-08-22
 */
public class GuoPdfUtil {

    public static void main(String[] args) throws IOException, DocumentException, TemplateException {
        String pdfDest ="D:\\doc_test\\aaa.pdf";
        String html ="D:\\doc_test\\";
//        ftlToString(String ftlDir, String ftlName, Map paramMap)
        Map m = new HashMap();
        m.put("orderBillCode","aaass");
        m.put("billDate","aaass");
        m.put("billMoney","aaass");
        m.put("customerAddress","aaass");
        m.put("customerName","customerNamecustomerNamecustomerName");

        String tmpHtml =  GuoFtlUtil.ftlToString(html,"aaa.ftl",new HashMap());
        GuoPdfUtil.htmlTemplateToPdf(tmpHtml,pdfDest);
    }


    /**
     * html模板的String生成pdf
     *
     * @param htmlTemplate
     * @param pdfPathName
     * @throws IOException
     * @throws DocumentException
     */
    public static void htmlTemplateToPdf(String htmlTemplate, String pdfPathName) throws IOException, DocumentException {
        File pdf = new File(pdfPathName);
        if (!pdf.getParentFile().exists()) {
            pdf.getParentFile().mkdirs();
        }
        if (pdf.exists()) {
            pdf.delete();
        }
        Document document = new Document(PageSize.LETTER);
        PdfWriter pdfWriter = PdfWriter.getInstance(document,
                new FileOutputStream(pdfPathName));
        XMLWorkerHelper worker = XMLWorkerHelper.getInstance();
        document.open();
        worker.parseXHtml(pdfWriter, document, new ByteArrayInputStream(htmlTemplate.getBytes("UTF-8")), Charset.forName("UTF-8"), new ChinaFontProvide());
        document.close();
    }


    /**
     *
     * 提供中文
     *
     */
    public static final class ChinaFontProvide implements FontProvider {

        @Override
        public Font getFont(String arg0, String arg1, boolean arg2, float arg3,
                            int arg4, BaseColor arg5) {
            BaseFont bfChinese = null;
            try {
                bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",
                        BaseFont.NOT_EMBEDDED);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
            return FontChinese;
        }

        @Override
        public boolean isRegistered(String arg0) {
            return false;
        }
    }

    /**
     * 字体类
     */
    public static class AsianFontProvider extends XMLWorkerFontProvider {


        public AsianFontProvider() {
            super(null, null);
        }

        //    @Override
    public Font getFont(final String fontname, String encoding, float size, final int style) {
        String fntname = fontname;
        if (fntname == null) {
            /**
             * 使用的windows里的宋体，可将其文件放资源文件中引入
             */
            String os = System.getProperties().getProperty("os.name");
            if (os.startsWith("win") || os.startsWith("Win")) {
                fntname = "STFANGSO";
            } else {
                fntname = "STFANGSO";
            }
            fntname = "宋体";
        }
        if (size == 0) {
            size = 4;
        }
        System.out.print("-----fntname:"+fntname);
        return super.getFont(fntname, encoding, size, style);
    }

//        @Override
//        public Font getFont(String fontname, String encoding, boolean embedded, float size, int style, BaseColor color) {
//            //字体文件路径
//            String name = "";
//            //华文仿宋
//            String fontNameDefault = "Alibaba_PuHuiTi_2.0_35_Thin_35_Thin.ttf";
//            if (fontname != null) {
//                /**
//                 * 可以在html中指定字体，如在body中指定：font-family: SimSun.ttc;
//                 */
//                fontNameDefault = fontname;
//            }
//            String os = System.getProperties().getProperty("os.name").toLowerCase();
//            if (os.startsWith("win")) {
//                name = "G:\\dev\\gitee\\nit-random-tools\\src\\main\\resources\\ttfs\\" + fontNameDefault + "";
//            } else {
//                name = "/data/eco/billpdf/ftl/" + fontNameDefault + "";
//            }
//            //如果是ttc，需要如下处理
//            if (name.toLowerCase().contains("ttc")) {
//                name += ",1";
//            }
//            Font font = null;
//            try {
//                font = new Font(BaseFont.createFont(name, BaseFont.IDENTITY_H, BaseFont.EMBEDDED));
//                font.setStyle(style);
//                font.setColor(color);
//                if (size > 0) {
//                    font.setSize(size);
//                }
//            } catch (DocumentException e) {
//                e.printStackTrace();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//            return font;
//        }
    }

}

